package com.lk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 循环输出
 * ABCABC
 */
public class TestAlternate {
    public static void main(String[] args) {
        DemoAlternate demoAlternate = new DemoAlternate();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                demoAlternate.loopA(i);
            }
        },"A");

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                demoAlternate.loopB(i);
            }
        },"B");

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                demoAlternate.loopC(i);
            }
        },"C");

    }
}

class DemoAlternate{
    int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void loopA(int totalLoop){
        lock.lock();
        try {
            if(num!=1){
                try {
                    condition1.await();
                } catch (InterruptedException e) {
                }
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i+"  "+totalLoop);
            }
            num = 2;
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void loopB(int totalLoop){
        lock.lock();
        try {
            if(num!=2){
                try {
                    condition2.await();
                } catch (InterruptedException e) {
                }
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i+"  "+totalLoop);
            }
            num = 3;
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void loopC(int totalLoop){
        lock.lock();
        try {
            if(num!=3){
                try {
                    condition3.await();
                } catch (InterruptedException e) {
                }
            }
            for (int i = 0; i < 20; i++) {
                System.out.println(Thread.currentThread().getName()+"  "+i+"  "+totalLoop);
            }
            num = 3;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }

}
